/*****************************************************************************************
 * Dexter : Distributed Experimental and Tester Platform
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *****************************************************************************************/
package dexter.net;

import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.SessionLog;

import dexter.net.msg.RequestMessage;
import dexter.net.msg.ResponseMessage;
import dexter.net.msg.common.ResponseListener;
import dexter.net.msg.common.RequestParams;


public class ProducerSessionHandler extends IoHandlerAdapter {
	
    private final RequestParams params;
    private ResponseListener listener;

    private boolean finished;

    public ProducerSessionHandler(RequestParams params, ResponseListener listener) {
        this.params = params;
        this.listener = listener;
    }

    public boolean isFinished() {
        return finished;
    }

    public void sessionOpened(IoSession session) {
        
        RequestMessage m = new RequestMessage();
        m.setParams(params);
        session.write(m);
        
    }

    public void messageReceived(IoSession session, Object message) {
        
    	if (message instanceof ResponseMessage) {
        	
          ResponseMessage rm = (ResponseMessage) message;
          
          if (rm.isOk()) {
            // server returned OK code.
        	// return result and disconnect.
            SessionLog.info(session, "Test succesfully");
            session.close();
            finished = true;   
            listener.resultArrive(rm.getResult());
          } else {
            // seever returned error code because of overflow, etc.
            SessionLog.warn(session, "Server error, disconnecting...");
            session.close();
            finished = true;
            listener.errorArrive(rm.getResult());
          }
       }   
    }

    public void exceptionCaught(IoSession session, Throwable cause) {
        session.close();
    }
}